package com.rfy.novel.chain.client;



import com.rfy.base.constant.enums.WebsiteEnum;
import com.rfy.framework.util.HttpUtil;
import com.rfy.novel.entity.Book;
import com.rfy.novel.entity.BookCatalogue;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rfy.base.constant.NovelConstant.*;


/**
 * @author zhanghuiyong
 * @创建时间 2019年05月31日
 * @描述: 新笔趣网小说检索
 **/
public class SearchWebsiteMiaoJiang extends SearchWebsite {
    public static void main(String[] args) {
        SearchWebsiteMiaoJiang miaoJiang = new SearchWebsiteMiaoJiang();
        miaoJiang.readingNovel(NOVEL_NAME_DQDYJ, 190);
    }


    /**
     * 网站搜索接口
     *
     * @param keyWord 关键字（小说名称）
     * @return book 书籍实体
     */
    @Override
    public Book searchWebsite(String keyWord) {
        //转码
        String keyWordEncode = null;
        try {
            keyWordEncode = URLEncoder.encode(keyWord, CODE_GBK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String searchUrl = WebsiteEnum.WEBSITE_MIAOJIANG.getSearchUrl();
        //构建请求参数实体
        Map<String, Object> params = new HashMap<>();
        params.put("type", "articlename");
        params.put("s", keyWordEncode);
        params.put("submit", "");
        String searchResult = HttpUtil.sendPostX(searchUrl, params, CODE_GBK);
        //book-img-text
        //解析文档
        Document doc = Jsoup.parse(searchResult);
        //获取根据 cover class 获取所有的目录章节
        Elements elementsByClass = doc.getElementsByClass("cover");
        //默认第一个class   根据p标签获取搜索书籍
        Element elementByPTag = elementsByClass.get(0).getElementsByTag("p").first();

        //根据第二个 a标签 获取书籍信息
        Element bookElementByTag = elementByPTag.getElementsByTag("a").get(1);

        //取书籍名称
        String bookName = bookElementByTag.text();
        System.out.println("查询书籍名称:" + bookName);
        //根据属性获取书籍地址
        String bookUrl = STRING_MIAOJIANG_SURL + bookElementByTag.attributes().get("href");
        //获取书籍简介
        String bookSynopsis = null;

        Book mjBook = new Book();
        mjBook.setBookName(bookName);
        mjBook.setBookUrl(bookUrl);
        mjBook.setBookSynopsis(bookSynopsis);
//        //现在不需要模糊查询，如果检索的和查询结果的不一致就返回结果
//        if (!keyWord.equals(bookName)) {
//            return null;
//        }
        return mjBook;
    }

    @Override
    public Book getNovelCatalogueList(Book book) {
        List<BookCatalogue> catalogueList = new ArrayList<>();
        //书籍编号计数器
        Integer codeNumber = 0;

        String searchResult = HttpUtil.doGet(book.getBookUrl(), CODE_GBK);
        //解析文档
        Document doc = Jsoup.parse(searchResult);
        //根据chapterList id 获取书籍目录
        Element cataloguesByBox = doc.getElementById("chapterList");

        //a 标签 获取免费章节
        Elements cataloguesByATyp = cataloguesByBox.getElementsByTag("a");
        for (Element element : cataloguesByATyp) {
            //获取章节标题
            String title = element.text();
            //获取书籍章节的地址
            String href = STRING_MIAOJIANG_SURL + element.attributes().get("href");

            //书籍内容预处理
            BookCatalogue bookCatalogue = new BookCatalogue();
            bookCatalogue.setType(BOOT_TYPE_NVIP);
            bookCatalogue.setId(codeNumber);
            bookCatalogue.setTitle(title);
            bookCatalogue.setHref(href);
            catalogueList.add(bookCatalogue);
            codeNumber++;
        }
        book.setCatalogueList(catalogueList);

        return book;
    }

    @Override
    public Book getNovel(String keyWord) {
        Book book = this.searchWebsite(keyWord);
        Book catalogueList = this.getNovelCatalogueList(book);
        return catalogueList;
    }

    @Override
    public BookCatalogue getNovelContent(BookCatalogue bookCatalogue) {
        if (null == bookCatalogue || StringUtils.isEmpty(bookCatalogue.getHref())) {
            return null;
        }
//        String contentResult = HttpUtilS.doGet(bookCatalogue.getHref(), CODE_GBK);

        String contentResult = HttpUtil.doGet(bookCatalogue.getHref(), CODE_GBK);


        //解析文档
        Document doc = Jsoup.parse(contentResult);
        // 根据id nr1 获取内容
        Element contentElement = doc.getElementById("nr1");
        String contentStr = contentElement.toString();
        bookCatalogue.setChapterContent(contentStr);
        return bookCatalogue;
    }

    @Override
    public String websiteType() {
        return WebsiteEnum.WEBSITE_MIAOJIANG.getWebsiteName();
    }

}
